package com.scau.phr.common.util;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.scau.phr.common.exceptions.ServiceException;

import static com.scau.phr.common.exceptions.ErrorCode.DATABASE_OPERATE_ERRPR;
import static com.scau.phr.common.exceptions.ErrorCode.UNKNOW_ERROR;

public class TransactionalTool {
    public interface Operate{
        /**
         * 数据库操作
         * @param obj
         * @return
         */
        int dbOperate(BaseMapper mapper,Object obj);

        /**
         * 其他操作
         * @param obj
         * @return
         */
         boolean otherOperate(Object obj);

        /**
         * 返回true则将ohterOperate覆盖缺省操作
         * @return
         */
         boolean Cancel();
    }
    public static boolean transOperate(Operate operate, BaseMapper mapper,Object obj){
        try{
            int n=operate.dbOperate(mapper,obj);
            if(!operate.Cancel()) {
                if(n>0){
                    return  true;
                }
                else throw new ServiceException(DATABASE_OPERATE_ERRPR);
            }
            else return operate.otherOperate(obj);
        } catch (Exception e) {
            throw new ServiceException(UNKNOW_ERROR,e.getMessage());
        }
    }
}
